<template>
	<view class="e-p-t-20 e-p-l-20 e-p-r-20" :style="[AppSkinVar]">
		<e-loading-page :loading="loading || payLoading">
			<template #icon>
				<loader></loader>
			</template>
		</e-loading-page>
		<DeliveryTabs v-if="deliveryTabList && deliveryTabList.length > 1" v-model:value="receivingType" :list="deliveryTabList" @change="handleChangeReceivingType"></DeliveryTabs>
		<template v-if="[1, 3, 5].includes(receivingType)">
			<order-address v-show="!isVirtualGoods" class="e-m-b-20 e-m-t-10" v-model:info="address" type="1" v-if="address"></order-address>
			<!-- 2023/11/20马来提出，虚拟商品需要增加一个联系方式，方便商家联系买家 -->
			<view class="e-flex e-p-20 bg-white e-m-b-20" v-if="isVirtualGoods">
				<view class="e-flex-1">
					{{ $t('tools.lxfs') }}
				</view>
				<e-input inputAlign="right" v-model="contactPhone" :placeholder="$t('tools.qsrlxfs')" border="none" clearable></e-input>
			</view>
		</template>
		<view class="custom-order-list" v-for="(item, index) in orderVos" :key="index">
			<PreviewOrderGoodsItem :store="item" :goodsList="item.canList" :noCanList="item.noCanList"
				:exceedLimitList="item.exceedLimitList" @showReason="handleShowReason" class="e-m-b-20">
				<view class="custom-order-list-form bg-f7 e-p-20 e-m-b-20" v-if="goods.formJson">
					<goods-layout-form-popup replyInfo :formJson="goods.formJson" :subType="type === '2' ? 2: 1"
						:price="goods.deputyMoney" :number="goods.commodityCount"
						@edit="getData"></goods-layout-form-popup>
				</view>
				<!-- <template #deduction="{ goods }" v-if="deductionOpen === 'Y'">
					<view class="e-flex-xy-center e-flex-between e-font-28 c-666 e-p-l-20" :data-url="goods" @tap="(e:any) => handleTapDiscount(goods, e)">
						<text>{{ $t('classify.抵扣优惠') }}</text>
						<view class="e-flex-1 text-right c-red">
							<text v-if="goods.deputyMoneyDeduction">- {{ goods.deputyMoneyDeduction }}</text>
						</view>
						<app-image src="arrow_right.png" :size="['28rpx']" />
					</view>
				</template> -->
				<template #storeCoupon v-if="item.params && item.params.coupon && item.params.coupon.couponList.length">
					<view class="e-flex-xy-center e-flex-between e-font-28 c-666 e-p-l-20" @tap="handleOpenCoupon(2, item.storeId)">
						<text>{{ $t('classify.店铺优惠') }}</text>
						<view class="e-flex-1 text-right c-red">-{{ item.orderMoneyCoupon }}</view>
						<app-image src="arrow_right.png" :size="['36rpx']" />
					</view>
				</template>
				<template #orderVos>
					<view class="" v-if="[3, 5].includes(receivingType) && item.canList && item.canList.length">
						<DeliveryTime
							:key="deliveryTimeKey"
							:orderVos="item"
							v-if="item.fig"
							:orderDeliveryfee="item.orderDeliveryfee"
							@setDeliveryTime="setDeliveryTime"
							:receivingType="receivingType"
							:deliveryTimes="deliveryTimes"
						></DeliveryTime>
					</view>
					<view class="" v-if="receivingType === 2 && item.canList && item.canList.length">
						<StoreAddressSelect
							v-if="receivingIds && receivingIds.length"
							:receivingIds="receivingIds"
							:storeId="item.storeId"
							@setPredictTime="setPredictTime"
							@updateReceivingIds="updateReceivingIds"
						></StoreAddressSelect>
					</view>
					<view class="e-flex bg-white e-font-28 c-333 e-p-t-20 e-p-b-10" v-if="item.canList && item.canList.length">
						<text class="e-m-r-76">{{ $t('classify.订单备注') }}</text>
						<e-input
							style="z-index: 1"
							:placeholder="$t('classify.请填写备注信息')"
							border="none"
							v-model="remarks[item.storeId]"
							placeholderClass="placeholder-class"
						></e-input>
					</view>
				</template>
			</PreviewOrderGoodsItem>
		</view>

		<view class="e-m-t-20 e-p-20 bg-white e-radius-20">
			<view class="e-p-b-25">
				<text class="fw-600">{{ $t('classify.价格明细') }}</text>
			</view>
			<view class="e-flex e-flex-between">
				<text>{{ $t('order.商品总价') }}</text>
				<text>{{ $unitEn }}{{ info.money }}</text>
			</view>
			<view class="e-flex e-m-t-34" @tap="handleOpenCoupon(1)" v-if="showCoupon">
				<text>{{ $t('order.平台优惠') }}</text>
				<view class="e-flex-1 text-right c-red">
					<text v-if="info.couponMoney">-{{ $unitEn }}{{ info.couponMoney }}</text>
				</view>
				<image class="img-36" :src="$staticPath('classify/arrow-right.png')" mode=""></image>
			</view>
			<view class="e-flex e-flex-between e-m-t-34">
				<text>{{ $t('order.运费') }}</text>
				<text class="c-red">+{{ $unitEn }}{{ info.freight || info.deliveryfee }}</text>
			</view>
			<view class="e-flex e-flex-between e-m-t-34" v-if="info.moneyDeduction">
				<text>{{ $t('order.抵扣') }}</text>
				<text class="c-red">-{{ $unitEn }}{{ info.moneyDeduction }}</text>
			</view>
			<view class="e-flex e-flex-between e-m-t-34" v-if="info.moneyDis">
				<text>{{ $t('order.优惠') }}</text>
				<text class="c-red">-{{ $unitEn }}{{ info.moneyDis }}</text>
			</view>
			<view class="e-flex e-flex-between e-m-t-34">
				<text>合计</text>
				<text>{{ $unitEn }}{{ info.payMoney }}</text>
			</view>
		</view>
		<view class="e-radius-20  overflow-hidd e-m-b-20" v-show="deductionList.length || giveList.length">
			<view class="e-flex e-m-t-20 e-p-t-24 e-p-b-24 e-p-l-30 bg-white fw-600">
				{{ $t('nearby.deduction') }}
			</view>
			<view class="bg-white">
				<view class="preview-order-mode" v-for="item in deductionList" :key="item.strategy">
					<view class="preview-order-mode__mask" @tap="handleTapDeductionItem(item, 1)"></view>
					<view class="e-flex e-p-b-20">
						<view class="e-m-r-10">
							<load-image size="32rpx" :src="item.icon"></load-image>
						</view>
						<text class="e-font-24 c-regular">{{ item.name }}</text>
						<text class="e-font-24 c-regular">积分抵扣</text>
					</view>
					<e-line color="#E6E6E6"></e-line>
					<view class="e-flex e-flex-between e-p-t-20">
						<text class="fw-600">{{ $unitEn }}{{ item.payMoney }} + {{ item.floatingMoney }}{{ item.name }}</text>
						<view class="e-flex">
							<radio
								:disabled="!item.deductMoney"
								:color="AppSkin.primary"
								:value="`${item.strategy}`"
								:checked="item.check"
								@tap.stop="handleTapDeductionItem(item, 1)"
							/>
						</view>
					</view>
				</view>
				<template v-if="giveList.length">
					<view class="preview-order-mode" v-for="item in [giveList[0]]" :key="item.strategy">
						<view class="preview-order-mode__mask" @tap="handleTapDeductionItem(item, 2)"></view>
						<view class="e-flex e-p-b-20">
							<view class="e-m-r-10">
								<image src="/pages/systemPay/static/nearby/icon.png" class="img-32 e-m-r-10"></image>
							</view>

							<text class="e-font-24 c-regular">原价购买</text>
						</view>
						<e-line color="#E6E6E6"></e-line>
						<view class="e-flex e-flex-between e-p-t-20">
							<text class="fw-600">{{ $unitEn }}{{ item.payMoney }}</text>
							<view class="e-flex">
								<radio :color="AppSkin.primary" :value="`${item.strategy}`" :checked="!deductionModeId.length" @tap.stop="handleTapDeductionItem(item, 2)" />
							</view>
						</view>
					</view>
				</template>
			</view>
		</view>

		<!-- <view class="bg-white border-radius-20 e-p-l-20 e-p-r-20 e-p-t-30 e-p-b-30 e-m-t-20 e-flex e-font-28 c-333 coupon-share-box e-m-b-20">
			<text class="fw-600 e-m-r-30">{{ $t('advanceShare.优惠券码') }}</text>
			<e-input
				style="z-index: 1; width: 100px"
				:placeholder="$t('advanceShare.请输入优惠券码')"
				border="none"
				v-model="couponShareCode"
				placeholderClass="placeholder-class"
			></e-input>
		</view> -->
		<view class="bg-white e-radius-20 overflow-hidd">
			<view class="e-p-l-20 e-p-r-20 e-p-t-25 e-p-b-25">
				<text class="fw-600">{{ $t('nearby.支付方式') }}</text>
			</view>
			<pay-list ref="payListRef" :hasDFK="true" :isTrace="!!isTrace" :isDefault="isTrace ? 'N' : 'Y'" :proIds="proIds"></pay-list>
		</view>
		<view class="bg-white e-radius-20 e-p-l-20 e-p-r-20 e-p-t-30 e-p-b-30 e-m-t-20 e-flex e-font-28 c-333 coupon-share-box">
			<view class="w-600 e-m-r-30">发票</view>
			<view class="e-flex e-flex-1 justify-end" @tap="showInvoice = true">
				<text class="" v-if="Object.keys(invoiceData).length">电子（商品明细-{{invoiceData.billToType === 1 ? '个人':'公司'}}）</text>
				<image class="img-36" :src="$staticPath('arrow_right.png')" mode=""></image>
			</view>
		</view>
		<password-popup ref="passwordPopupRef" :payMoney="info.payMoney" :show="show" @close="show = false" @confirm="passwordPay"></password-popup>

		<view style="height: 140rpx"></view>
		<view class="fixed-button e-flex e-flex-between bg-white">
			<view class="e-flex e-flex-between">
				<text class="e-font-30">{{ $t('cart.总计') }}：</text>
				<text class="c-red e-font-36">{{ $unitEn }}{{ info.payMoney }}</text>
			</view>
			<button class="bg-primary c-white" @tap="buy(true)">{{ $t('classify.去支付') }}</button>
		</view>
		<!-- 账户选择弹窗 -->
		<DiscountPop
			v-model:show="discountPopShow"
			:deductionType="deductionType"
			v-model:deductionStrategy="deductionStrategy"
			:selectedCommodityUrl="selectedCommodityUrl"
			:deductionMode="deductionMode"
			:deputyMoneyDeduction="deputyMoneyDeduction"
			@submit="handleChangeSelect"
		></DiscountPop>

		<!-- 优惠券详情 -->
		<CouponPop v-model:value="showCouponPop" v-model:couponList="couponList" :isPlat="isPlat" @changeCouponStatus="changeCouponStatus" @closeUse="closeUse"></CouponPop>

		<!-- 不可下单原因 -->
		<NoCanReason v-model:value="showReason" :noCanList="noCanList" :exceedLimitList="exceedLimitList" :receivingType="receivingType"></NoCanReason>

		<!-- 提示添加收货地址 -->
		<e-modal :show="showAddrPop" :confirmText="$t('classify.去添加')" @confirm="handleJumpAddress" @cancel="$back()">
			<view class="slot-content">
				{{ $t('classify.请先添加收货地址') }}
			</view>
		</e-modal>
		<card-valid-code-popup :show="cardValidCodePopupShow" :payMoney="info.payMoney" @cancel="handleCancelCardPay" @confirm="handleCardPay"></card-valid-code-popup>
	
		<invoiceVue v-model:value="showInvoice" @close="showInvoice =false" @submit="submitInvoice"></invoiceVue>
		<!-- 绑定推广人 -->
		<e-popup :show="showAddParentPhone" mode="center" bgColor="transparent"  round="20rpx">
			<view class="add-parent-phone bg-white e-radius-20 e-rela">
				<image :src="$staticPath('order/close.png')" class="img-28 add-parent-phone__close" mode="" @tap="handleCancelParentPhone"></image>
				<view class="e-flex-xy-center e-m-b-38 e-p-t-40" >
					<text class="e-font-32 w-600">邀请人</text>
				</view>
				<view class="e-p-l-46 e-p-r-44 e-m-b-56">
					<view class="add-parent-phone__input e-flex-y-center">
						<input type="tel" name="" v-model="phone" id="" placeholder="请输入邀请人手机号码"  align="center" style="align-items: center;width:100%"/>
					</view>
				</view>
				<view class="e-flex-xy-center">
					<view class="add-parent-phone__btn add-parent-phone__btn1 e-m-r-20 e-flex-xy-center"  @tap="handleCancelParentPhone">
						<text class="e-font-30 w-500 c-333">取消</text>
					</view>
					<view class="add-parent-phone__btn e-flex-xy-center" :style="{background:AppSkin.primary}" @tap="handleBindPhone">
						<text class="e-font-30 w-500 c-white">确定</text>
					</view>
				</view>
			</view>
		</e-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { debounce, throttle } from '@/common/utils';
import {
	postPreviewOneGoodsOrder,
	postPurchaseOneGoods,
	postPreviewCartGoodsOrder,
	postPurchaseCartGoods,
	postAgainCreateGoods,
	postAgainPurchaseGoods,
	getPayResult,
	getOrderQueryActivity,
	getAddressList,
	getDeliveryPlaceList,
	receiveSecurities,
	getCouponByShare,
	postSupperAppBindRecommender
} from '@/common/request/api';
import type {
	PurchaseGoodsParams,
	PreviewOrderData,
	AddressItem,
	OrderCouponsItem,
	OrderGoods,
	DeliveryPlace,
	PurchaseGoodsPayData,
	DeductionStrategy,
	deductionAccountItem,
} from '@/common/request/api';
import { useCurrentInstance, useLocation } from '@/common/hooks';
import DiscountPop from './child/discount/index.vue';
import CouponPop from './child/coupon';
import DeliveryTabs from './child/deliveryTabs.vue';
import DeliveryTime from './child/deliveryTime.vue';
import StoreAddressSelect from './child/store-address.vue';
import NoCanReason from './child/noCanReason.vue';
import PreviewOrderGoodsItem from './child/goodsItem.vue';
import CardValidCodePopup from '../child/cardValidCodePopup.vue';
import { useUser, useShoppingCart } from '@/common/stores';
import { storeToRefs } from 'pinia';
import { onLoad, onShow } from '@dcloudio/uni-app';
import type { Mutable } from '@/typings/utils';
import type { UniGlobalData } from '@/typings/uni';
import { usePay } from '../hooks/usePay';
import type { PayListInstance, PasswordPopupInstance } from '@/typings/components';
import { PayType } from '@/env';
import invoiceVue from './child/invoice.vue';
const userStore = useUser()
const props = defineProps({
	type: {
		type: String,
		required: true
	}, //下单类型 1单商品 2购物车 3多商品或订单重购买
	qty: String, //单商品下单参数
	skuId: String, //单商品下单参数
	basketIds: String, //购物车下单参数
	buys: String, //多商品下单参数
	isTrace: String, // 是否来自视频带货
	receivingType: String,
	aId: String
});

const ctx = useCurrentInstance();

const { payLoading, systemPay, cardValidCodePopupShow, checkCardPay, handleCancelCardPay, handleCardPay, getH5PayResult } = usePay();

const pageParams: Partial<Mutable<typeof props>> = { ...props };
delete pageParams.isTrace;
delete pageParams.aId;
delete pageParams.type;

const { getCart } = useShoppingCart();
const { userInfo } = storeToRefs(useUser());

const { latitude, longitude, getUserLocation } = useLocation();

const loading = ref(true);
const showInvoice = ref(false)
const invoiceData = ref({})

const submitInvoice = (data) => {
	invoiceData.value = data
	showInvoice.value = false
}

const showAddParentPhone = ref(false)
const phone = ref()
const cancleParentPhone = ref(false)
const handleCancelParentPhone=() =>{
	showAddParentPhone.value = false
	cancleParentPhone.value = true
}
const handleBindPhone=()=> {
	if (!phone.value) return
	showAddParentPhone.value = false
	postSupperAppBindRecommender({phone:phone.value}).then(res => {
		if (res.code == 200) {
			userStore.getUserInfo()
			ctx.$toastApp('绑定成功')
		}
	})
}

// receivingType 商品发货类型：2-快递 3-闪送 4-核销 5-自提 6-配送 pre接口
// receivingType 订单收货方式 ：1快递 2自提 3-闪送 4-核销 5-配送 pay接口
const receivingType = ref(1);
if (props.receivingType) {
	switch (props.receivingType) {
		case '2':
			receivingType.value = 1;
			break;
		case '3':
			receivingType.value = 3;
			break;
		case '4':
			receivingType.value = 4;
			break;
		case '5':
			receivingType.value = 2;
			break;
		case '6':
			receivingType.value = 5;
			break;
	}
} else {
	receivingType.value = 1;
}

const info = ref<PreviewOrderData>({
	orderVos: [],
	storeReceiving: false,
	money: 0,
	moneyDis: 0,
	payMoney: 0,
	freight: 0,
	deliveryfee: 0,
	moneyDeduction: 0,
	couponMoney: 0,
	couponMoneySys: 0,
	deliveryModes: [],
	delivery: false
});
const getCanList = (item: OrderGoods) =>
	item.deputys.filter((items) => {
		// isFlash 0 不可以下单 1可以
		if (receivingType.value === 3 && items.isFlash) {
			if (!items.flashDeliveryLimit || (items.flashDeliveryLimit && items.commodityCount <= items.flashDeliveryLimit)) {
				return items;
			}
		} else if (items.isFlash) {
			return items;
		}
	});

const orderVos = computed(() => {
	return info.value.orderVos.map((item) => {
		return {
			...item,
			// isFlash 0 不可以下单 1可以
			canList: getCanList(item),
			noCanList: item.deputys.filter((item) => !item.isFlash),
			// 超出闪送数量
			exceedLimitList:
				receivingType.value === 3
					? item.deputys.filter((deputy) => {
							return deputy.isFlash && deputy.flashDeliveryLimit && deputy.commodityCount > deputy.flashDeliveryLimit;
					  })
					: []
		};
	});
});

// 虚拟商品联系方式
const contactPhone = ref(userInfo.value.phone || '');
let preQueryData = ''; //预览订单数据
const couponShareCode = ref(''); //优惠券码
let isFirstCouponShare = false; //是否首次领取券码
let couponShareId = ''; //优惠券码获取的优惠券id
const couponId = ref(''); //当前选中的优惠券

watch(couponShareCode, () => {
	handleReceivingCoupon();
});

const showCouponPop = ref(false); // 优惠券弹窗

const address = ref<AddressItem | undefined>(undefined);
const handleSelectAddress = (e: AddressItem) => {
	address.value = e;
};

const showAddrPop = ref(false);
const handleJumpAddress = () => {
	ctx.$goTo(
		'/pages/user/receivingAddress/index',
		{ type: 1 },
		{
			selectAddress: handleSelectAddress
		}
	);
	showAddrPop.value = false;
};

const show = ref(false);

const storeId = ref(''); // 当前操作的店铺
const storeAddress = ref<DeliveryPlace | undefined>(undefined);

watch(address, (newValue) => {
	if (newValue?.id && !loading.value) {
		getData();
	}
});

const discountPopShow = ref(false); // 抵扣弹窗
const deductionStrategy = ref<DeductionStrategy[]>([]);
const deductionOpen = ref('N'); // 是否开启抵扣 N 关闭 Y 开启
const deductionMode = ref('N'); // 抵扣模式 是否足额抵扣 N 不足额抵扣 Y 足额抵扣
const deductionType = ref('N'); // 抵扣方式 N 单账户 Y 多账户

const selectedCommodityUrl = ref(''); // 当前选中的商品图片

let selectDeductionStrategy: Record<string, string> = {}; // 当前选中的抵扣
const getDeductionStrategy = () => (Object.keys(selectDeductionStrategy).length ? JSON.stringify(selectDeductionStrategy) : undefined);

const deputyMoneyDeduction = ref<number | null>(null); // 当前操作项抵扣额
const commoditySpecId = ref(''); // 当前选中的规格id

const paltFormCoupon = ref<OrderCouponsItem[]>([]); // 平台优惠券详情
const showCoupon = ref(false);
const isPlat = ref(false); // 是否平台优惠
const couponList = ref<OrderCouponsItem[]>([]);

const deliveryTabList = ref<
	{
		name: string;
		value: number;
	}[]
>([]);

// 不支持下单的商品列表
const noCanList = ref<OrderGoods['deputys']>([]);
//超出闪送数量限制的商品列表
const exceedLimitList = ref<OrderGoods['deputys']>([]);
const showReason = ref(false);

const deliveryTimes = ref<
	Array<{
		selectTime: string;
		deliveryTimes: string;
		storeId: string;
	}>
>([]); // 配送时间
const remarks = ref<Record<string, string>>({}); // 订单备注

const receivingIds = ref<
	Array<{
		predictTime?: string;
		storeId: string;
		storeAddress: DeliveryPlace;
	}>
>([]);

// 是否虚拟商品 虚拟商品不能加入购物车
const isVirtualGoods = ref(false);
const deliveryTimeKey = 'deliveryTimeKey'; //用于切换tab的时候初始化

const proIds = ref('');

watch(
	remarks,
	(val) => {
		if (val) {
			uni.setStorageSync('orderRemarks', val);
		}
	},
	{
		immediate: true,
		deep: true
	}
);

const handleReceivingCoupon = debounce(async function () {
	// 优惠券码
	if (couponShareCode.value.length === 16 && !isFirstCouponShare) {
		// 优惠券码 如果存在优惠券码，先领券,再通过券码获取优惠券id，这个优惠券id要和平台券和商家券一起传给后端
		try {
			await receiveSecurities(couponShareCode.value);
		} catch (e) {
			uni.removeStorageSync('couponShare');
			couponShareCode.value = '';
		}

		try {
			const result = await getCouponByShare({ couponShareCode: couponShareCode.value });
			if (result.data) {
				couponShareId = result.data;
			}
		} catch (e) {
			//TODO handle the exception
		}
		handleGetQueryOrderData();
	} else {
		couponShareId = '';
		handleGetQueryOrderData();
	}
}, 500);
const handleChangeReceivingType = () => {
	deliveryTimes.value = [];
	getData();
};
const setDeliveryTime = (val: (typeof deliveryTimes)['value'][0]) => {
	// 设置配送时间
	// 筛选掉不在订单内的店铺
	const orderStoreIds = info.value.orderVos.map((item) => item.storeId);
	const deliveryTime = deliveryTimes.value.filter((item) => orderStoreIds.includes(item.storeId));
	const index = deliveryTime.findIndex((item) => item.storeId === val.storeId);
	if (index >= 0) {
		deliveryTime.some((item) => {
			if (item.storeId === val.storeId) {
				item.selectTime = val.selectTime;
				item.deliveryTimes = val.deliveryTimes;
				return true;
			}
		});
	} else {
		deliveryTime.push(val);
	}
	deliveryTimes.value = deliveryTime;
	uni.setStorageSync('deliveryTimes', deliveryTime);
};
const setPredictTime = (predictTime: string, _storeId: string) => {
	receivingIds.value?.some((item) => {
		if (item.storeId === _storeId) {
			item.predictTime = predictTime;
			return true;
		}
	});
	uni.setStorageSync('receivingIds', receivingIds.value);
};
const updateReceivingIds = (_storeAddress: DeliveryPlace) => {
	if (receivingIds.value && receivingIds.value.length) {
		receivingIds.value.some((item, index) => {
			if (item.storeId === _storeAddress.storeId) {
				receivingIds.value[index].storeAddress = _storeAddress;
			}
		});
	}
};
const handleShowReason = (list: OrderGoods['deputys'], list1: OrderGoods['deputys']) => {
	showReason.value = true;
	noCanList.value = list;
	exceedLimitList.value = list1;
};
const closeUse = () => {
	if (isPlat.value) {
		paltFormCoupon.value.forEach((item) => (item.check = false));
	} else {
		const index = info.value.orderVos.findIndex((item) => item.storeId === storeId.value);
		if (index > -1) {
			const item = { ...info.value.orderVos[index] };
			item.params?.coupon?.couponList.forEach((item) => (item.check = false));
			info.value.orderVos.splice(index, 1, item);
		}
	}
};
const handleOpenCoupon = (type: number, _storeId?: string) => {
	storeId.value = _storeId || '';
	if (type === 1) {
		couponList.value = paltFormCoupon.value;
		isPlat.value = true;
	} else {
		isPlat.value = false;
		info.value.orderVos.some((item) => {
			if (item.storeId === _storeId) {
				couponList.value = item.params?.coupon?.couponList || [];
			}
		});
	}
	showCouponPop.value = true;
};
const deductionModeId = ref<string[]>([]); //选中的抵扣账户
const deductionList = ref<deductionAccountItem[]>([]);
const giveList = ref<deductionAccountItem[]>([]);
const giveModeId = ref<string[]>([]); //选中的抵扣账户
const hasOriginal = ref(false);
const handleTapDeductionItem = (items: deductionAccountItem, type: number) => {
	if (type === 1) {
		if (items.deductMoney) {
			hasOriginal.value = false;
			if (deductionType.value === 'N') {
				deductionModeId.value = [items.strategy];
			} else {
				if (deductionModeId.value.includes(items.strategy)) {
					deductionModeId.value.splice(
						deductionModeId.value.findIndex((item) => item === items.strategy),
						1
					);
				} else {
					deductionModeId.value.push(items.strategy);
				}
			}
		}
		console.log(deductionModeId.value);
	} else {
		deductionModeId.value = [];
		giveModeId.value = [items.strategy];
	}

	handleGetQueryOrderData();
};

const getGiveStrategy = () => {
	let obj = {};
	const deductionStrategy = deductionModeId.value.join(',');
	info.value.orderVos.forEach((vos) => {
		vos.deputys.forEach((deputy) => {
			obj[deputy.commoditySpecId] = deductionStrategy;
		});
	});
	return {
		deductionStrategy: Object.keys(obj).length ? JSON.stringify(obj) : undefined,
		giveStrategy: giveModeId.value.join(',')
	};
};
// 获取活动数据
const handleGetQueryOrderData = () => {
	let couponIds: string[] = [];
	if (couponId.value) {
		couponIds = couponId.value.split(',');
	}
	if (couponShareId) couponIds.push(couponShareId);
	const params = {
		data: preQueryData,
		// deductionStrategy: getDeductionStrategy(),
		couponId: couponIds.length ? couponIds.join(',') : couponId.value,
		// 优惠券码
		couponShareCode: couponShareCode.value,
		...getGiveStrategy()
	};
	if (!params.data) return;
	loading.value = true;
	getOrderQueryActivity(params)
		.then((res) => {
			isFirstCouponShare = false;

			info.value = res.data.order;
			const goodsType: number[] = [];
			info.value.orderVos.forEach((item) => {
				goodsType.push(...item.deputys.map((deputy) => deputy.type));

				// 获取所有商品的id集
				proIds.value = item.deputys.map((item) => item.commodityId).join(',');
			});
			// 1 实物 2虚拟物品
			isVirtualGoods.value = goodsType.includes(2);
			paltFormCoupon.value = res.data.coupon || [];
			deductionList.value = (res.data.deductionList as deductionAccountItem[]) || [];
			deductionModeId.value = deductionList.value.filter((item) => item.check).map((item) => item.strategy);
			giveList.value = (res.data.giveList as deductionAccountItem[]) || [];
			giveModeId.value = giveList.value?.[0]?.check ? [giveList.value?.[0]?.strategy] : [];
			if (paltFormCoupon.value && paltFormCoupon.value.length) showCoupon.value = true;
			const deduction = res.data.deduction;
			if (deduction) {
				deductionOpen.value = deduction.deductionOpen;
				deductionMode.value = deduction.deductionMode;
				deductionType.value = deduction.deductionType;
			}
			handleCalcDeduction();
		})
		.finally(() => {
			loading.value = false;
		});
};

const handleCalcDeduction = (obj?: DeductionStrategy[], isOpen?: number) => {
	const strategyMap: Record<string, string> = {};
	info.value.orderVos.forEach((vos) => {
		vos.deputys.forEach((deputy) => {
			// 判断是否是当前操作的商品
			const strategy: string[] = [];
			if (deputy.commoditySpecId === commoditySpecId.value && obj) {
				if (isOpen) {
					obj?.forEach((item) => {
						if (item.check) {
							strategy.push(item.strategy);
						}
					});
				}
				strategyMap[deputy.commoditySpecId] = strategy.join(',');
			} else {
				deputy?.params?.deductionStrategy?.forEach((item) => {
					if (item.check) {
						strategy.push(item.strategy);
					}
					strategyMap[deputy.commoditySpecId] = strategy.join(',');
				});
			}
		});
	});
	selectDeductionStrategy = strategyMap;
};
const handleChangeSelect = (obj: DeductionStrategy[], isOpen: number) => {
	discountPopShow.value = false;

	handleCalcDeduction(obj, isOpen);
	handleGetQueryOrderData();
};
const handleTapDiscount = (data: OrderGoods['deputys'][0], event: { currentTarget: { dataset: { url: OrderGoods['deputys'][0] } } }) => {
	// #ifdef MP-WEIXIN
	data = event.currentTarget.dataset.url;
	// #endif
	deductionStrategy.value = data.params ? data.params.deductionStrategy : [];
	selectedCommodityUrl.value = data.commodityUrl;
	discountPopShow.value = true;
	commoditySpecId.value = data.commoditySpecId;
	deputyMoneyDeduction.value = data.deputyMoneyDeduction;
};
// 更改优惠券选择
const changeCouponStatus = (list: OrderCouponsItem[]) => {
	let couponIds: string[] = [];
	if (isPlat.value) {
		list.some((item) => {
			if (item.check) {
				couponIds.push(item.id);
				return true;
			}
		});
	} else {
		paltFormCoupon.value.some((item) => {
			if (item.check) {
				couponIds.push(item.id);
				return true;
			}
		});
	}
	info.value.orderVos.forEach((vos) => {
		if (vos.storeId === storeId.value) {
			list.some((item) => {
				if (item.check) {
					couponIds.push(item.id);
					return true;
				}
			});
		} else {
			vos.params?.coupon?.couponList.some((item) => {
				if (item.check) {
					couponIds.push(item.id);
					return true;
				}
			});
		}
	});
	couponId.value = couponIds.length ? couponIds.join(',') : '';
	handleGetQueryOrderData();
};

let deputys: {
	buys: { qty: string; sku: string }[];
} = props.buys
	? JSON.parse(props.buys)
	: {
			buys: []
	  };
const getData = async () => {
	try {
		let params = {
			...pageParams,
			receivedId: address.value?.id,
			receivingType: receivingType.value,
			couponShareCode: couponShareCode.value
		};
		let res: PreviewOrderData;
		loading.value = true;
		switch (props.type) {
			case '1':
				const res1 = await postPreviewOneGoodsOrder({
					...params,
					qty: props.qty || '',
					skuId: props.skuId || ''
				});
				res = res1.data;
				break;
			case '2':
				const res2 = await postPreviewCartGoodsOrder({
					...params,
					basketIds: props.basketIds || ''
				});
				res = res2.data;
				break;
			default:
				const res3 = await postAgainCreateGoods({
					...params,
					buys: props.buys || ''
				});
				res = res3.data;
				break;
		}

		loading.value = false;

		preQueryData = JSON.stringify(res);
		if (receivingType.value === 2) {
			receivingIds.value = [];
			getUserLocation().finally(() => {
				res?.orderVos?.forEach((item) => {
					getDeliveryPlaceList({
						storeId: item.storeId,
						location: longitude.value ? `${longitude.value},${latitude.value}` : ''
					}).then((_res) => {
						let params = {
							storeId: item.storeId,
							storeAddress: _res.data[0]
						};
						receivingIds.value.push(params);
					});
				});
			});
		}
		// receivingType 订单收货方式 ：1快递 2自提 3-闪送 4-核销 5-配送 pay接口
		const deliveryModes = res.deliveryModes;
		if (deliveryModes) {
			const arr: (typeof deliveryTabList)['value'] = [];
			if (deliveryModes.includes('3')) {
				arr.push({
					name: ctx.$t('classify.闪送'),
					value: 3
				});
			}
			if (deliveryModes.includes('6')) {
				arr.push({
					name: ctx.$t('classify.配送'),
					value: 5
				});
			}
			if (deliveryModes.includes('2')) {
				arr.push({
					name: ctx.$t('classify.快递'),
					value: 1
				});
			}
			if (deliveryModes.includes('5')) {
				arr.push({
					name: ctx.$t('classify.自提'),
					value: 2
				});
			}
			deliveryTabList.value = arr;
		}
	} catch (e) {
		loading.value = false;
	}

	// 优惠券码 如果存在优惠券码，先领券,再通过券码获取优惠券id，这个优惠券id要和平台券和商家券一起传给后端
	const couponShare = uni.getStorageSync('couponShare');
	if (couponShare) {
		const _couponShareCode = couponShare.couponShareCode;
		if (_couponShareCode) {
			const receiveCouponResult = await receiveSecurities(_couponShareCode);
			if (receiveCouponResult.code !== 200) {
				uni.removeStorageSync('couponShare');
				couponShareCode.value = '';
			}
			const result = await getCouponByShare({ couponShareCode: _couponShareCode });
			if (result.code == 200 && result.data) {
				couponShareId = result.data;
			}
			isFirstCouponShare = true;
			couponShareCode.value = _couponShareCode;
		}
	}
	handleGetQueryOrderData();
};
const payListRef = ref<PayListInstance>();
const buy = throttle(function () {
	if (isVirtualGoods.value && !contactPhone.value) {
		ctx.$toastApp(ctx.$t('tools.qsrlxfs'));
		return;
	}
	if ([1, 3, 5].includes(receivingType.value) && !address.value?.id) {
		ctx.$toastApp(ctx.$t('classify.请先添加收货地址再支付'));
		return;
	}
	if (receivingType.value === 2) {
		let flag = false;
		receivingIds.value.some((item) => {
			if (item.predictTime && !item.storeAddress) {
				flag = true;
				return true;
			}
		});
		if (flag) {
			ctx.$toastApp(ctx.$t('classify.请先选择自提点'));
			return;
		}
	}
	// 闪送或者配送
	if ([3, 5].includes(receivingType.value)) {
		if (!deliveryTimes.value || !deliveryTimes.value.length) {
			if (receivingType.value === 3) {
				ctx.$toastApp(ctx.$t('classify.当前位置不支持闪送'));
			} else {
				ctx.$toastApp(ctx.$t('classify.当前位置不支持配送'));
			}
			return;
		} else if (!deliveryTimes.value[0].selectTime) {
			ctx.$toastApp(ctx.$t('classify.请选择预计送达时间'));
			return;
		}
		// 判断是否达到起送价 orderStartPrice
		let flag = info.value.orderVos.some((item) => {
			if (item.fig) {
				const fig = JSON.parse(item.fig);
				if (item.orderMoney < fig.orderStartPrice) {
					ctx.$toastApp(ctx.$t('classify.订单未达起送价'));
					return true;
				}
			} else {
				if (receivingType.value === 3) {
					ctx.$toastApp(ctx.$t('classify.当前位置不支持闪送'));
				} else {
					ctx.$toastApp(ctx.$t('classify.当前位置不支持配送'));
				}
				return true;
			}
		});
		if (!flag) {
			flag = info.value.orderVos.every((item) => !getCanList(item).length);
		}

		if (flag) return;
	}
	if(!userInfo.value.parentPhone && !cancleParentPhone.value) {
		// 如果没有推广人，要绑定推广人
		showAddParentPhone.value = true
		return
	}
	if (!payListRef.value?.payItem) {
		ctx.$toastApp(ctx.$t('nearby.请选择支付方式'));
		return;
	}

	if (info.value.payMoney) {
		if (payListRef.value.payItem.type === 'SYS') {
			show.value = true;
		} else {
			pay(payListRef.value.payItem.id, undefined, payListRef.value.payItem.type);
		}
	} else {
		// 如果支付金额为0，默认取第一个支付方式，默认支付密码为sanxinjava
		//  如果有余额账号默认余额，没有则取第一个
		let arr = payListRef.value?.payMode?.filter((item) => item.isDefault === 'Y');
		if (!arr || !arr.length) {
			arr = payListRef.value?.payMode;
		}
		if (arr && arr.length) {
			const item = arr[0];
			pay(item.id, 'sanxinjava', PayType.SYS);
		} else {
			ctx.$toastApp(ctx.$t('order.平台暂未开放支付'));
		}
	}
}, 1000);

const passwordPopupRef = ref<PasswordPopupInstance>();
const passwordPay = (password: string) => {
	passwordPopupRef.value?.reset();
	show.value = false;
	pay(payListRef.value.payItem.id, password, payListRef.value.payItem.type);
};
// 支付
const pay = throttle(async function (payId: number, payword: string | undefined = undefined, payType: PayType, bankId?: number) {
	let couponId = [];
	if (couponShareId) couponId.push(couponShareId);
	if (paltFormCoupon.value.length) {
		paltFormCoupon.value.some((item) => {
			if (item.check) {
				couponId.push(item.id);
				return true;
			}
		});
	}
	info.value.orderVos.forEach((item) => {
		if (item.params && item.params.coupon && item.params.coupon.couponList.length) {
			item.params.coupon.couponList.some((list) => {
				if (list.check) {
					couponId.push(list.id);
					return true;
				}
			});
		}
	});
	// 自提
	const _receivingIds =
		receivingType.value === 2
			? receivingIds.value
					.map((item) => {
						if (item.storeAddress) {
							return {
								receivingId: item.storeAddress.id,
								storeId: item.storeId,
								predictTime: item.predictTime
							};
						}
						return null;
					})
					.filter((item) => item)
			: [];

	const _couponIds = new Set(couponId);
	const _remarks: { storeId: string; remark: string }[] = [];
	if (remarks.value) {
		Object.keys(remarks.value).forEach((item) => {
			_remarks.push({
				storeId: item,
				remark: remarks.value[item]
			});
		});
	}
	let params: PurchaseGoodsParams = {
		...pageParams,
		receivingId: storeAddress.value?.id,
		couponId: Array.from(_couponIds).join(','),
		// 订单类型：1快递 2自提 3-闪送 4-核销 5-配送
		receivingType: receivingType.value,
		// 优惠券码
		couponShareCode: couponShareCode.value,
		// 虚拟商品需要填写联系方式
		// virtuallyProPhone: contactPhone.value,
		// 闪送或者配送
		deliveryTimes: [3, 5].includes(receivingType.value) ? JSON.stringify(deliveryTimes.value) : '',
		receivingIds: _receivingIds.length ? JSON.stringify(_receivingIds) : '',
		remarks: _remarks.length ? JSON.stringify(_remarks) : '',
		deductionStrategy: props.type === '3' ? '' : getDeductionStrategy(),
		fromType: getApp<UniGlobalData>().globalData?.payFromType,
		receivedId: address.value?.id,
		payId,
		payword
	};
	
	
	let requireOrder = false;
	// #ifdef MP-WEIXIN
	if (props.isTrace) {
		let traceRes = await checkBeforeAddOrder();
		if (traceRes.code === 200) {
			params['traceId'] = traceRes.traceId;
			requireOrder = traceRes.requireOrder === 1;
		}
	}
	// #endif
	if (
		!bankId &&
		checkCardPay(payType, (cardId: number) => {
			pay(payId, payword, payType, cardId);
		})
	) {
		return;
	}
	
	if (Object.keys(invoiceData.value).length) {
		params.hasInvoice = 1
		params.orderInvoicesStr = JSON.stringify(invoiceData.value)
	} else {
		params.hasInvoice = 0
	}
	
	
	uni.hideLoading();
	if (payType===PayType.DFK) {
		payLoading.value = false;
		// 如果是代付，则保存订单数据
		const orderParams = {
			data:params,
			type:props.type,
			isTrace: props.isTrace,
			requireOrder,
			payType,
			payResultApi: getPayResult
		}
		uni.setStorageSync('orderParams',JSON.stringify(orderParams))
		uni.navigateTo({
			url:'/pages/systemPay/proxyOrder/order?money='+info.value.payMoney
		})
		return
	}
	let res: PurchaseGoodsPayData;
	try {
		switch (props.type) {
			case '1':
				res = await postPurchaseOneGoods({
					...params,
					qty: props.qty || '',
					skuId: props.skuId || '',
					bankId
				});
				break;
			case '2':
				res = await postPurchaseCartGoods({
					...params,
					bankId,
					basketIds: orderVos.value
						.map((item) => {
							return item.canList.map((items) => items.basketId).join(',');
						})
						.join(',')
				});
				break;
			default:
				const buysParams = {
					buys: deputys.buys.map((item) => {
						return {
							qty: item.qty,
							sku: item.sku,
							deductionStrategy: getDeductionStrategy()
						};
					}),
					bankId
				};
				res = await postAgainPurchaseGoods({
					...params,
					buys: JSON.stringify(buysParams)
				});

				break;
		}
		payLoading.value = false;
		
		const payStatus = await systemPay({
			payType,
			resolveData: res,
			api: getPayResult,
			storageKey: 'payOrderId',
			payUrl: res.data,
			payParams: res.data,
			successUrl: (id: string) => `order/success?type=4&id=${id}`,
			errorUrl: (msg: string) => `order/error?msg=${msg}`,
			orderUrl: 'order/index?type=1',
			isTrace: !!props.isTrace,
			requireOrder,
			payMoney: info.value.payMoney
		});
		if (typeof payStatus === 'boolean') {
			return;
		}
		if (props.type === '2') {
			getCart();
		}
		uni.removeStorageSync('couponShare');
	} catch (e) {
		ctx.$goTo(`/pages/order/error?msg=${e}`);
	}
}, 1500);

// #ifdef MP-WEIXIN
const checkBeforeAddOrder = (): Promise<{
	traceId: string;
	requireOrder: number;
	code: number;
}> => {
	return new Promise((resolve, reject) => {
		wx.checkBeforeAddOrder({
			success: (res) => {
				resolve({
					traceId: res.data.traceId,
					requireOrder: res.data.requireOrder,
					code: 200
				});
			},
			fail: (err: any) => {
				reject({
					code: 500
				});
				console.log(err);
			}
		});
	});
};
// #endif
let isLoad = true;
onLoad(() => {
	getAddressList()
		.then((res) => {
			if (res.data.length) {
				if (props.aId) {
					address.value = res.data.find((item) => `${item.id}` == props.aId);
				}
				if (!address.value) {
					address.value = res.data.find((item) => item.isDefaul === 1);
				}
			} else {
				showAddrPop.value = true;
			}
		})
		.finally(() => {
			getData();
		});
	// #ifdef HTML5 || PREVIEW
	getH5PayResult('order/success', 'payOrderId', getPayResult);
	// #endif
});
onShow(() => {
	if (isLoad) {
		isLoad = false;
	} else {
		if (!address.value) {
			getAddressList()
				.then((res) => {
					if (res.data.length) {
						address.value = res.data.find((item) => item.isDefaul === 1) || res.data[0];
					} else {
						showAddrPop.value = true;
					}
				})
				.finally(() => {
					getData();
				});
		}
	}
	storeAddress.value = uni.getStorageSync('storeAddressInfo') || undefined;
	deliveryTimes.value = uni.getStorageSync('deliveryTimes') || [];
	remarks.value = uni.getStorageSync('orderRemarks') || {};
});
</script>

<style lang="scss" scoped>
	::v-deep {

		.coupon-share-box .uni-input-input,
		.custom-order-list .uni-input-input {
			text-align: right;
		}

		.custom-order-list-form .uni-input-input {
			text-align: left;
		}
	}

.fixed-button {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	height: 112rpx;
	padding: 0 28rpx;
	z-index: 1;

	button {
		width: 240rpx;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 40rpx;
		margin: 0;
	}
}

.placeholder-class {
	text-align: right;
}
.preview-order-mode {
	padding: 20rpx 32rpx;
	position: relative;

	&__mask {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		z-index: 1;
	}
}
.justify-end {
	justify-content: flex-end;
}
.add-parent-phone {
		width: 670rpx;
		height: 450rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		&__close {
			position: absolute;
			top: 42rpx;
			right: 24rpx;
		}
		&__input {
			width: 580rpx;
			height: 120rpx;
			box-shadow: inset 0px -1prx 0px 0px #EDED
		}
		&__btn {
			width: 280rpx;
			height: 100rpx;
			border-radius: 50rpx;
		}
		&__btn1 {
			border:1rpx solid #ccc;
			color:#ccc;
		}
	}
</style>